package com.lovo.dao.impl;

import com.lovo.bean.CommentBean;
import com.lovo.dao.ICommentDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Repository
public class CommentDaoImpl extends BaseDao implements ICommentDao {
    @Override
    public List<CommentBean> findAllCommentByPostId(int id) {
        List<CommentBean> list=new ArrayList<>();
        this.setConnection();
        try {
            ps= con.prepareStatement("SELECT c.* FROM t_post p,t_comment c WHERE p.pk_postId=c.fk_postId AND c.fk_postId=?");
            ps.setObject(1,id);
            rs= ps.executeQuery();
            while (rs.next()){
                CommentBean com=new CommentBean();
                com.setId(rs.getInt("pk_commentId"));
                com.setTittle(rs.getString("c_title"));
                com.setMessage(rs.getString("c_msg"));
                com.setLocalDateTime((LocalDateTime) rs.getObject("c_time"));
                com.getUser().setUserId(rs.getInt("fk_userId"));
                com.getPostBean().setId(rs.getInt("fk_postId"));

                list.add(com);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
        return list;
    }

    @Override
    public void addComment(CommentBean comment) {
        this.setConnection();
        try {
            ps=con.prepareStatement("INSERT INTO t_comment(c_title,c_msg,c_time,fk_userId,fk_postId) VALUES(?,?,?,?,?)");
            ps.setObject(1,comment.getTittle());
            ps.setObject(2,comment.getMessage());
            ps.setObject(3,comment.getLocalDateTime());
            ps.setObject(4,comment.getUser().getUserId());
            ps.setObject(5,comment.getPostBean().getId());

            ps.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.closeConnection();
        }
    }
}
